//
//  LKTools.m
//  SUOTA
//
//  Created by   on 2022/5/9.
//  Copyright © 2022 Dialog Semiconductor. All rights reserved.
//

#import "LKTools.h"
NSString * const OTAS_DIR = @"otas";
@implementation LKTools

+ (void)copyFileFromResourceTOSandbox:(NSArray<NSURL *> *)fileUrls
{
    
    [fileUrls.firstObject startAccessingSecurityScopedResource];
    
    
    NSFileCoordinator *fileCoordinator = [[NSFileCoordinator alloc] init];
    NSError *error;
    
    [fileCoordinator coordinateReadingItemAtURL:fileUrls.firstObject options:0 error:&error byAccessor:^(NSURL *newURL) {
        //
        NSString *fileName = [newURL lastPathComponent];
        NSError *error = nil;
        NSData *fileData = [NSData dataWithContentsOfURL:newURL options:NSDataReadingMappedIfSafe error:&error];
        
        if (error) {
            // 读取出错
        } else {
            // 上传
            DebugNSLog(@"fileName : %@", fileName);
            NSString * appDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
            NSString *directryPath = [appDir stringByAppendingPathComponent:OTAS_DIR];
            NSError *fileError;
            BOOL isCreate = [[NSFileManager defaultManager] createDirectoryAtPath:directryPath withIntermediateDirectories:YES attributes:nil error:&fileError];
            if (fileError) {
                DebugNSLog(@"%@", fileError);
            }
            
            
            NSString *path = [directryPath stringByAppendingPathComponent:fileName];
            [[NSFileManager defaultManager] copyItemAtURL:fileUrls.firstObject toURL:[NSURL fileURLWithPath:path] error:&fileError];
            if (fileError) {
                DebugNSLog(@"copy %@", fileError);
            }
            
        }
    }];
    [fileUrls.firstObject stopAccessingSecurityScopedResource];
    
    
}

@end
